import wx

from utils import tracer
from wx.aui import AuiManager as MDIClient

class UIManager(object):
  def __init__(self, name):
    self._uiParent = None
    self._items = None
    self._name = name
    self._menus = None
    self._toolbars = None

  def load(self, pluginMgr):
    pass

  def unload(self):
    pass

  def attach(self, uiParent):
    pass

  def detach(self):
    pass

  def getName(self):
    return self._name

  def createMenus(self, uiParent):
    return None

  def getToolbars(self, uiParent):
    if self._toolbars is None:
      self._toolbars = self.createToolbars(uiParent)
    return self._toolbars

  def createToolbars(self, uiParent):
    return None

  def getItemByName(self, name):
    if self._items is None:
      return None
    if self._items.has_key(name):
      return self._items[name]
    return None

  def getItems(self):
    if self._items is None:
      return None
    return self._items.values()

  def getMenus(self, uiParent):
    if self._menus is None:
      self._menus = self.createMenus(uiParent)
    return self._menus

  def getMenuItemByCaption(self, caption):
    menus = self.getMenus(None)
    if menus is None:
      return None

    for menu in menus:
      menuItem = self.findMenuItem(menu[1], caption)
      if menuItem is None:
        continue
      return menuItem

    return None

  def findMenuItem(self, menu, caption):
    if menu is None:
      return None
    
    if type(menu) is wx.MenuItem:
      if menu.GetText() ==  caption:
        tracer.writeln('Target Caption: %s, Menu Item: %s' % (caption, menu.GetText()))
        return menu
      elif menu.IsSubMenu():
        tracer.writeln('Target Caption: %s, Sub Menu: %s' % (caption, menu.GetText()))
        subMenu = menu.GetSubMenu()
        tracer.writeln('Target Caption: %s, Menu: %s, Menu Item Count: %d' % (caption, subMenu.GetTitle(), subMenu.GetMenuItemCount()))
        for menuItem in subMenu.GetMenuItems():
          re = self.findMenuItem(menuItem, caption)
          if not re is None:
            return re
    elif type(menu) is wx.Menu and menu.GetMenuItemCount() > 0:
      tracer.writeln('Target Caption: %s, Menu: %s, Menu Item Count: %d' % (caption, menu.GetTitle(), menu.GetMenuItemCount()))
      for menuItem in menu.GetMenuItems():
        re = self.findMenuItem(menuItem, caption)
        if not re is None:
          tracer.writeln('Target menu found. Menu Item: %s' % menuItem.GetText())
          return re

    return None
